# Create your views here.
from django.http import HttpResponse
from django.shortcuts import render_to_response
from cites.models import *
import random

# get a random cite
def random_cite( req ):
    total = Cite.objects.count()
    cite = Cite.objects.get( id = random.randint(1,total))
    comments = Comment.objects.filter( cite = cite )
    return render_to_response('main.html',locals())

# add a new cite to site
def add_cite( req ):
    cite = req.REQUEST['cite']
    if len(cite) > 0:
        try:
            c = Cite( cite = cite )
            c.save()
        except:
            return HttpResponse('{success: false}')
    return HttpResponse('{success: true}')

# add a comment to existing cite
def add_comment( req ):
    cid = int(req.REQUEST['cid'])
    comment = req.REQUEST['comment']
    if len(comment) > 0:
        cite = Cite.objects.get( id = cid )
        try:
            if cite is not None:
                cmt = Comment( comment = comment, cite = cite)
                cmt.save()
        except:
            return HttpResponse('{success: false}')
    return HttpResponse('{success: true}')

# increase or decrease rating of cite
def rate_up( req ):
    cid = int(req.REQUEST['cid'])
    cite = Cite.objects.get( id = cid )
    if cite is not None:
        cite.rate += 1
        cite.save()
    return HttpResponse('{success: true, rate: %d}' % cite.rate )

def rate_down( req ):
    cid = int(req.REQUEST['cid'])
    cite = Cite.objects.get( id = cid )
    if cite is not None:
        cite.rate -= 1
        cite.save()
    return HttpResponse('{success: true, rate: %d}' % cite.rate )

# implement some kind of search here
def search( req ):
	pass


# list of best rated cites
def best_rated( req ):
	cites = Cite.objects.all().order_by('rate')[:10]
	return render_to_response('best_rated.html',locals())
